<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8">
        <title>好看的文件上传组件</title>
        <style>
            .file-upload-wrapper {
                display: inline-flex;
                width: 300px;
                height: 30px;
                line-height: 30px;
                border: 1px solid blue;
                border-radius: 5px;
                user-select: none;
            }

            .file-upload-wrapper>.file-selector {
                flex-basis: 80%;
            }

            .file-upload-wrapper>input[type=file] {
                display: none;
            }

            .file-upload-wrapper>.upload-button {
                flex-basis: 20%;
                background: #6e6eff;
                color: #fff;
                text-align: center;
                cursor: pointer;
            }

            .file-upload-wrapper>.upload-button:hover {
                background: #2b2bff;
            }
        </style>
    </head>
    <body>
        <h3>可能是好看的文件上传组件</h3>
        <div>
            <label>头像</label>
            <div class="file-upload-wrapper">
                <input type="file">
                <span class="file-selector">请选择待上传的文件</span>
                <span class="upload-button">上传</span>
            </div>
        </div>

        <script>
            const input = document.querySelector('.file-upload-wrapper>input[type=file]');
            const fileSelector = document.querySelector('.file-selector');
            const uploadButton = document.querySelector('.upload-button');

            // 监听 input 上的 change 事件
            input.addEventListener('change', ()=>{
                let files = input.files;
                console.log( files );
                let f = files[0];
                console.log( f );
                let name = f.name ;
                console.log( name );
                fileSelector.innerHTML = name ;
            },false);

            fileSelector.addEventListener('click', () => {
                // 调用 input 元素的 click 函数实现"点击"操作
                input.click();
            }, false);

            uploadButton.addEventListener('click', ()=>{
                let files = input.files;
                if( files.length === 0 ) {
                    alert('请先选择文件'); // Window.prototype.alert
                    // let content = prompt('请告知你不选择文件的理由'); // Window.prototype.prompt
                    return;
                }
                let result = confirm('确定上传文件吗?'); // Window.prototype.confirm
                console.log( result );
                if( result ) {
                    // 后续可以用 JavaScript 实现异步文件上传
                }
            }, false);
        </script>
    </body>
</html>